package net.top.viewer.managers
{
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	
	import net.top.viewer.AppEvent;
	import net.top.viewer.utils.Hashtable;
	
	/**
	 * Data manager will be storing the session data to support data reuse such as widget chain.
	 */
	public class DataManager extends EventDispatcher
	{
		private var dataTable:Hashtable;
		
		public function DataManager(target:IEventDispatcher=null)
		{
			super(target);
			
			dataTable = new Hashtable();
			AppEvent.addListener(AppEvent.CONFIG_LOADED, configLoadedHandler);
			
			// This is an example to set up the listener to get the type of data the Data
			// Manager is interested in.
			AppEvent.addListener(AppEvent.DATA_FETCH_ALL, fetchAllData);
			AppEvent.addListener(AppEvent.DATA_PUBLISH, addData);
			AppEvent.addListener(AppEvent.DATA_FETCH, fetchData);
		}
		
		private function configLoadedHandler(event:AppEvent):void
		{
		}
		
		private function fetchAllData(event:AppEvent):void
		{
			AppEvent.dispatch(AppEvent.DATA_SENT, dataTable);
		}
		
		private function fetchData(event:AppEvent):void
		{
			var key:String = event.data.key as String;
			var data:Object =
				{
					key: key,
					collection: dataTable.find(key)
				};
			AppEvent.dispatch(AppEvent.DATA_SENT, data);
		}
		
		private function addData(event:AppEvent):void
		{
			var key:String = event.data.key;
			if (key)
			{
				var dataCollection:Object = event.data.collection;
				if (dataTable.containsKey(key))
				{
					dataTable.remove(key);
				}
				dataTable.add(key, dataCollection);
				
				var data:Object =
					{
						key: key,
						data: dataTable
					};
				AppEvent.dispatch(AppEvent.DATA_NEW_PUBLISHED, data);
			}
		}
	}
}